package com.dongwu.manager.web;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.aliyun.oss.OSSClient;
import com.baidu.ueditor.define.FileType;
import com.dongwu.common.constants.OSSClientConstants;
import com.dongwu.common.dto.Result;
import com.dongwu.common.utils.FileTypeUtils;
import com.dongwu.config.AliyunOSSClientUtil;
import com.dongwu.config.AliyunVodForOSS;
import com.gexin.fastjson.JSON;

/**
 * 单图片上传,多图片上传，apk上传,音频上传，视频上传
 * 
 * @author xyj
 * @date 2017年9月20日
 */
@Controller
@RequestMapping("/file")
public class OSSUploadFileController {

	protected Logger logger = LoggerFactory.getLogger(this.getClass());

	private static Map<String, Object> callBackMap = new HashMap<String, Object>();

	private static final String image = "image/"; // 图片文件在oss上的文件夹

	private static final String apk = "apk/"; // apk文件在oss上的文件夹

	private static final String audio = "audio/"; // music文件在oss上的文件夹

	// private static final String video = "video/"; // video文件在oss上的文件夹

	private static final String title = "广投墙视频";// 广投墙点播视频标题

	/**
	 * 单图上传
	 * 
	 * @param Multfile
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/uploadOneImage", method = RequestMethod.POST)
	@ResponseBody
	public Result uploadOneImage(@RequestParam(value = "file", required = false) MultipartFile Multfile,
			HttpServletRequest request) {
		String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/";
		String suffix = FileType.getSuffixByFilename(Multfile.getOriginalFilename());
		if (!FileTypeUtils.isImage(suffix)) {
			return Result.errorResult("文件格式不支持！");
		}
		// 获取oss目标路径
		String ossPath = FileTypeUtils.OSSFileTargetPath(image);
		File file = FileTypeUtils.MultipartFileToNewFile(Multfile, filePath);
		// 初始化OSSClient
		OSSClient ossClient = AliyunOSSClientUtil.getOSSClient();
		String md5key = AliyunOSSClientUtil.uploadObject2OSS(ossClient, file, OSSClientConstants.BACKET_NAME, ossPath);

		List<String> Url = new ArrayList<String>();
		Url.add(OSSClientConstants.DOMAIN_HTTP + ossPath + file.getName());
		Url.add(String.valueOf(file.length()));
		Url.add(md5key);
		return Result.successResult(Url);
	}

	/**
	 * 视频上传
	 * 
	 * @param file
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/uploadVideo", method = RequestMethod.POST)
	@ResponseBody
	public Result uploadVideo(@RequestParam(value = "file", required = false) MultipartFile Multfile,
			HttpServletRequest request) {
		List<String> Url = new ArrayList<String>();
		String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/";
		// 获取文件后缀
		String suffix = FileType.getSuffixByFilename(Multfile.getOriginalFilename());
		if (!FileTypeUtils.isVideo(suffix)) {
			return Result.errorResult("文件格式不支持！");
		}
		// 文件转存
		File file = FileTypeUtils.MultipartFileToNewFile(Multfile, filePath);

		String videoId = AliyunVodForOSS.uploadVideo(file, title);
		//循环判断阿里云视频转码完成事件
		for (int i = 0; i >= 0; i++) {
			try {
				Thread.sleep(1000);
				if (callBackMap.containsKey(videoId)) {
					//res = AliyunVodForOSS.getVideoUrl(videoId);
					Url.add(callBackMap.get(videoId).toString());
					Url.add(String.valueOf(file.length()));
					break;
				}
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
//		List<String> Url = new ArrayList<String>();
//		Map<String, Object> PlayInfoList = (Map<String, Object>) res.get("PlayInfoList");
//		List<Map<String, Object>> PlayInfo = (List<Map<String, Object>>) PlayInfoList.get("PlayInfo");
//		Url.add(PlayInfo.get(1).get("PlayURL").toString());
//		Url.add(String.valueOf(file.length()));
		return Result.successResult(Url);
	}

	/**
	 * 阿里云上传视频文件回调
	 * 
	 * @param file
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/upVideoCallBack", method = RequestMethod.POST)
	@ResponseBody
	public Result upVideoCallBack(@RequestBody String jsonBody) {
		Map<String, Object> map = JSON.parseObject(jsonBody);
		if (map.get("Status").toString().equals("success")) {
			// 如果回调是视频转码完成
			if (map.get("EventType").toString().equals("TranscodeComplete")) {
				List<Map<String, Object>> StreamInfos = (List<Map<String, Object>>) map.get("StreamInfos");
				for (Map<String, Object> StreamInfo : StreamInfos) {
					if(StreamInfo.get("Format").equals("mp4")){
						//将视频id和视频地址保存到map
						callBackMap.put(map.get("VideoId").toString(), StreamInfo.get("FileUrl").toString());
					}
				}
				
			}
		}
		return Result.successResult();
	}

	/**
	 * 上传apk文件
	 * 
	 * @param Multfile
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/uploadApk", method = RequestMethod.POST)
	@ResponseBody
	public Result uploadApk(@RequestParam(value = "file", required = false) MultipartFile Multfile,
			HttpServletRequest request) {
		String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/";
		String suffix = FileType.getSuffixByFilename(Multfile.getOriginalFilename());
		if (!FileTypeUtils.isApk(suffix)) {
			return Result.errorResult("文件格式不支持！");
		}
		// 获取oss目标路径
		String ossPath = FileTypeUtils.OSSFileTargetPath(apk);
		File file = FileTypeUtils.MultipartFileToNewFile(Multfile, filePath);
		// 初始化OSSClient
		OSSClient ossClient = AliyunOSSClientUtil.getOSSClient();
		String md5key = AliyunOSSClientUtil.uploadObject2OSS(ossClient, file, OSSClientConstants.BACKET_NAME, ossPath);
		List<String> Url = new ArrayList<String>();
		Url.add(OSSClientConstants.DOMAIN_HTTP + ossPath + file.getName());
		Url.add(String.valueOf(file.length()));
		Url.add(md5key);
		return Result.successResult(Url);
	}

	/**
	 * 上传音频文件
	 * 
	 * @param file
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/uploadAudio", method = RequestMethod.POST)
	@ResponseBody
	public Result uploadMusic(@RequestParam(value = "file", required = false) MultipartFile Multfile,
			HttpServletRequest request) {
		String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/";
		String suffix = FileType.getSuffixByFilename(Multfile.getOriginalFilename());
		if (!FileTypeUtils.isApk(suffix)) {
			return Result.errorResult("文件格式不支持！");
		}
		// 获取oss目标路径
		String ossPath = FileTypeUtils.OSSFileTargetPath(audio);
		File file = FileTypeUtils.MultipartFileToNewFile(Multfile, filePath);
		// 初始化OSSClient
		OSSClient ossClient = AliyunOSSClientUtil.getOSSClient();
		String md5key = AliyunOSSClientUtil.uploadObject2OSS(ossClient, file, OSSClientConstants.BACKET_NAME, ossPath);
		List<String> Url = new ArrayList<String>();
		Url.add(OSSClientConstants.DOMAIN_HTTP + ossPath + file.getName());
		Url.add(String.valueOf(file.length()));
		Url.add(md5key);
		return Result.successResult(Url);
	}
	// /**
	// * 多图上传
	// *
	// * @param file
	// * @param request
	// * @return
	// */
	// @RequestMapping(value = "/uploadManyImage", method = RequestMethod.POST)
	// @ResponseBody
	// public Result uploadManyImage(@RequestParam(value = "file", required =
	// false) MultipartFile[] Multfiles,
	// HttpServletRequest request) {
	// String filePath =
	// request.getSession().getServletContext().getRealPath("/") + "upload/";
	// // 初始化OSSClient
	// OSSClient ossClient = AliyunOSSClientUtil.getOSSClient();
	// for(Multfiles){
	//
	// }
	// String md5key = AliyunOSSClientUtil.uploadObject2OSS(ossClient,
	// MultipartFileToNewFile(Multfile, filePath),
	// OSSClientConstants.BACKET_NAME, OSSFileTargetPath(image));
	// List<String> Url = new ArrayList<String>();
	// Url.add(OSSClientConstants.DOMAIN_HTTP + OSSFileTargetPath(image) +
	// getFileName(Multfile));
	// Url.add(md5key);
	// return Result.successResult(Url);
	// return Result.errorResult("上传图片失败！");
	//
	// }
}
